package com.demo.springboot;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.valves.AccessLogValve;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 *   EmbeddedServletContainerCustomizer in spring boot 2.0 中
 * 用WebServerFactoryCustomizer<TomcatServletWebServerFactory>代替
 */
@Component
public class CustomizationBean  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        factory.setPort(3000);
        factory.setBaseDirectory(new File("F:/logs/tmp/"));
        factory.addInitializers((servletContext)->{
            System.out.println("===========servletContext startup==========");
            servletContext.setAttribute("startup","true");
        });
        factory.addContextValves(getAccessLogValve());
        factory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
    }

    private AccessLogValve getAccessLogValve(){
        AccessLogValve logValve = new AccessLogValve();
        logValve.setDirectory("F:/logs/access-log/");
        logValve.setEnabled(true);
        logValve.setPattern("common");
        logValve.setPrefix("spring-boot-demo17");
        logValve.setSuffix(".txt");
        return  logValve;
    }

    class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer{

        @Override
        public void customize(Connector connector) {
            System.out.println("===="+connector.getProtocol());
            System.out.println("===="+connector.getProtocolHandler().getClass().getName());
            Http11NioProtocol nioProtocol = (Http11NioProtocol)connector.getProtocolHandler();
            nioProtocol.setMaxConnections(2000);  // 设置最大的连接数
            nioProtocol.setMaxThreads(500);   // 设置最大的线程池数量
        }
    }
}
